/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.log.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.xrfzh.log.service.IOperationLogService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.xrfzh.common.entity.OperationLog;
import cn.xrfzh.common.entity.dto.OperationLogDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import cn.xrfzh.common.axios.AxiosEnum;
import cn.xrfzh.common.axios.AxiosResult;
import cn.xrfzh.common.exception.MyCustomException;
import cn.xrfzh.common.utils.ParallelStreamUtil;
import cn.xrfzh.log.mapper.OperationLogMapper;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 操作日志表
 *
 * @author fzh
 * @email e_341877120_mail@163.com
 * @date 2023-03-30 18:28:23
 */
@Service
@Transactional
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog>
		implements IOperationLogService {

	/**
	 * 根据条件查询列表
	 * @param operationLogDto
	 * @return
	 */
	@Override
	public AxiosResult selectList(OperationLogDto operationLogDto) {
		LambdaQueryWrapper<OperationLog> lqw;
		if (ObjectUtils.isEmpty(operationLogDto)) {
			lqw = null;
		}
		else {
			lqw = new LambdaQueryWrapper<>();
		}
		List<OperationLog> operationLogList = baseMapper.selectList(lqw);
		boolean flag = ObjectUtils.isNotEmpty(operationLogList);
		return flag ? AxiosResult.selectSuccess(operationLogList) : AxiosResult.selectError();
	}

	/**
	 * 根据条件分页查询
	 * @param currentPage
	 * @param pageSize
	 * @param operationLogDto
	 * @return
	 */
	@Override
	public AxiosResult selectPage(int currentPage, int pageSize, OperationLogDto operationLogDto) {
		IPage<OperationLog> iPage = new Page(currentPage, pageSize);
		LambdaQueryWrapper<OperationLog> lqw;
		if (ObjectUtils.isEmpty(operationLogDto)) {
			lqw = null;
		}
		else {
			lqw = new LambdaQueryWrapper<>();
			lqw.eq(StringUtils.isNotBlank(operationLogDto.getType()), OperationLog::getType, operationLogDto.getType())
					.like(StringUtils.isNotBlank(operationLogDto.getUserName()), OperationLog::getUserName,
							operationLogDto.getUserName());
		}
		iPage = page(iPage, lqw);
		boolean flag = ObjectUtils.isNotEmpty(iPage);
		return flag ? AxiosResult.selectSuccess(iPage) : AxiosResult.selectError();
	}

	/**
	 * 根据id查询单个
	 * @param id
	 * @return
	 */
	@Override
	public AxiosResult selectOneById(Long id) {
		if (ObjectUtils.isNotEmpty(id)) {
			OperationLog operationLog = getById(id);
			boolean flag = ObjectUtils.isNotEmpty(operationLog);
			return flag ? AxiosResult.selectSuccess(operationLog) : AxiosResult.selectError();
		}
		throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
	}

	/**
	 * 新增
	 * @param operationLogDto
	 * @return
	 */
	@Override
	public AxiosResult insert(OperationLogDto operationLogDto) {
		if (ObjectUtils.isNotEmpty(operationLogDto)) {
			boolean flag = save(operationLogDto);
			return flag ? AxiosResult.insertSuccess() : AxiosResult.insertError();
		}
		throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
	}

	/**
	 * 更新
	 * @param operationLogDto
	 * @return
	 */
	@Override
	public AxiosResult update(OperationLogDto operationLogDto) {
		if (ObjectUtils.isNotEmpty(operationLogDto)) {
			boolean flag = updateById(operationLogDto);
			return flag ? AxiosResult.updateSuccess() : AxiosResult.updateError();
		}
		throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
	}

	/**
	 * 根据id删除单个
	 * @param id
	 * @return
	 */
	@Override
	public AxiosResult delete(Long id) {
		if (ObjectUtils.isNotEmpty(id)) {
			boolean flag = removeById(id);
			return flag ? AxiosResult.deleteSuccess() : AxiosResult.deleteError();
		}
		throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
	}

	/**
	 * 根据id集合批量删除
	 * @param idList
	 * @return
	 */
	@Override
	public AxiosResult deleteBatch(List<Long> idList) {
		if (ObjectUtils.isEmpty(idList) || idList.size() == 0) {
			throw new MyCustomException(AxiosEnum.PARAMETER_ERROR);
		}
		boolean flag = removeByIds(idList);
		return flag ? AxiosResult.deleteSuccess() : AxiosResult.deleteError();
	}

	/**
	 * 导入文件
	 * @param file
	 * @return
	 */
	@Override
	public AxiosResult importFile(MultipartFile file) {
		boolean flag = false;
		try {
			InputStream inputStream = file.getInputStream();
			ExcelReader er = ExcelUtil.getReader(inputStream);
			List<OperationLog> operationLogList = er.readAll(OperationLog.class);
			flag = ParallelStreamUtil.insertBatchOfLarge(operationLogList, baseMapper::insertBatch);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return flag ? AxiosResult.success(AxiosEnum.IMPORT_SUCCESS) : AxiosResult.error(AxiosEnum.IMPORT_ERROR);
	}

	/**
	 * 导出文件
	 * @param response
	 */
	@Override
	public void exportFile(HttpServletResponse response) {
		try {
			List<OperationLog> operationLogList = list();
			ExcelWriter ew = ExcelUtil.getWriter(true);
			ew.setOnlyAlias(true);
			ew.write(operationLogList);
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
			String fileName = URLEncoder.encode("Excel导出表", "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
			ServletOutputStream sos = response.getOutputStream();
			ew.flush(sos, true);
			sos.close();
			IoUtil.close(sos);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

}
